package com.app.demo;

import static org.litepal.LitePalApplication.getContext;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.app.demo.fragments.FindFragment;
import com.app.demo.fragments.HomeFragment;
import com.app.demo.fragments.MineFragment;
import com.app.shop.mylibrary.base.BaseActivity;
import com.app.shop.mylibrary.base.BaseFragment;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class  MainActivity extends BaseActivity   {
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.tv2)
    TextView tv2;
    @BindView(R.id.tv3)
    TextView tv3;

    Fragment mFragment;
    BaseFragment fragment_home, fragment_find, fragment_mine;


    IntentFilter filter;
    SmsReceiver receiver;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSwipeEnabled(false);
        initFragment();
        MainActivity mm = new MainActivity();
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_SMS,Manifest.permission.RECEIVE_SMS}, 1);
        }
        filter=new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED" );
        receiver=new SmsReceiver();
        registerReceiver(receiver,filter);//注册广播接收器
    }

    public class SmsReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            StringBuilder content = new StringBuilder();//用于存储短信内容
            String sender = null;//存储短信发送方手机号
            Bundle bundle = intent.getExtras();//通过getExtras()方法获取短信内容
            String format = intent.getStringExtra("format");
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");//根据pdus关键字获取短信字节数组，数组内的每个元素都是一条短信
                for (Object object : pdus) {
                    SmsMessage message=SmsMessage.createFromPdu((byte[])object);//将字节数组转化为Message对象
                    sender = message.getOriginatingAddress();//获取短信手机号
                    content.append(message.getMessageBody());//获取短信内容

                }
            }

            if(judge(content.toString())){
                Handler handler=new Handler();
                Runnable runnable=new Runnable(){
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void run() {
                        Context mContext = getContext();
                        NotificationManager manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

                        String CHANNEL_ID = "com.example.test";//自定义的字符串
                        String CHANNEL_NAME = "TEST";
                        NotificationChannel notificationChannel = null;
                        NotificationCompat.Builder builder = null;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                            NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
                            notificationManager.createNotificationChannel(notificationChannel);
                        }

                        builder = new NotificationCompat.Builder(mContext, CHANNEL_ID).
                                setSmallIcon(R.mipmap.name_logo).
                                setContentTitle("反诈卫士提醒").
                                setStyle(new NotificationCompat.BigTextStyle().bigText("【紧急预警】您可能正遭遇短信诈骗，请务必提高警惕！")).

                                setWhen(System.currentTimeMillis()).
                                setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));


                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//SDK版本>=21才能设置悬挂式通知栏
                            builder.setCategory(String.valueOf(Notification.FLAG_ONGOING_EVENT))
                                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                                    .setColor(getResources().getColor(R.color.color_c5c8d1));
                        }
                        builder.setSmallIcon(R.mipmap.name_logo);
                        Notification notification = builder.build();
                        manager.notify(1, notification);
                    }
                };
                handler.postDelayed(runnable, 3000);
            }
            System.out.println(content);
        }

        //如果判断是垃圾短信，就返回true；
        public boolean judge(String messageContent){
            //同音字
            if(judgeGetPinYin(messageContent)){
                return true;
            }
            //同行字
            if(!judgeGetTongxinzi(messageContent)){
                return true;
            }
            //域名分析
            if(judgeGetYuMing(messageContent)){
                return true;
            }
            return false;
        }

        //判断同型词
        public boolean judgeGetTongxinzi(String messageContent){
            String str = messageContent;
            str=filtration(str);
            boolean result=judge1(str);
            return result;
        }
        public String filtration(String str){
            Pattern pattern=Pattern.compile("[\u0000-\u3DFF]");
            Matcher matcher=pattern.matcher(str);
            str=matcher.replaceAll("");//把汉字编码前面的消除
            return str;
        }
        public boolean judge1(String str){
            String[] key={"⁢Ｂ","𝐁","𝓑","Ḇ","B","𤢖","⺾","操","草","搞","稿","撸","㊤门","来⺾","㈰","䓍我","⁢寂⁢莫","⁢㊰⁢","+薇信","水多","加我矀","+徾","加微","+微","+薇","加∨","┿蓶","吱付宔","包中","必灜"};
            // String[] regexs={"[\s\S]*\\(陪)[\s\S]*\\(睡)[\s\S]*","[\s\S]*一天[\s\S]*左右[\s\S]*"};
            for(String s:key)
            {
                if(str.contains(s))
                {
                    System.out.println("有敏感词");
                    return false;
                }
            }
            return true;
        }

        //判断是否含有同音字，如果有的话就返回true；
        public boolean judgeGetPinYin(String messageContent){
            char[] t1 = null;
            t1 = messageContent.toCharArray();
            // System.out.println(t1.length);
            String[] t2 = new String[t1.length];
            // System.out.println(t2.length);
            // 汉字转拼音
            HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
            t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            t3.setVCharType(HanyuPinyinVCharType.WITH_V);
            String t4 = "";
            int t0 = t1.length;
            try {
                for (int i = 0; i < t0; i++) {
                    if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
                        t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);//
                        if(t2 != null){
                            t4 += t2[0];//
                        }
                    } else {
                        t4 += Character.toString(t1[i]);
                    }
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.fillInStackTrace();
            }
            //t4是得到的拼音序列
            //先匹配他是否还有wei 或者 zhi
            if(t4.indexOf("wei") != -1 || t4.indexOf("zhifubao") != -1 ){
                return true;
            }
            return false;
        }

        //判断是否含有繁体字
        private  void isSimpleOrComplex(String str, String encode) {
            try {
                if (str.equals(new String(str.getBytes(encode), encode))) {
                    System.out.println(str + "---是简体");

                }else{
                    System.out.println(str + "---是繁体");
                }
            } catch (Exception e) {
            }
        }

        //判断如果不是正规域名，返回true;
        public boolean judgeGetYuMing(String messageContent){
            String regex = "(((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6})";
            //sb存放正则匹配的结果
            StringBuffer sb = new StringBuffer();
            //编译正则字符串
            Pattern p = Pattern.compile(regex);
            //利用正则去匹配
            Matcher matcher = p.matcher(messageContent);
            //如果找到了我们正则里要的东西
            while (matcher.find()) {
                //保存到sb中，"\r\n"表示找到一个放一行，就是换行
                sb.append(matcher.group());
            }
            String needData = sb.toString();
            boolean result = needData.matches("((?!-)[A-Za-z]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}");
            boolean result2 = needData.matches("(((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+com)");
            boolean result3 = needData.matches("(((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+net)");
            boolean result4 = needData.matches("(((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+gov)");
            boolean result5 = needData.matches("(((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+org)");
            boolean result6 = needData.matches("(((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+cn)");
            boolean result7 = needData.matches("(((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+edu)");

            if(result == true){
                if (result2 == true || result3 == true || result4 == true || result5 == true
                        || result6 == true || result7 == true)
                    return false;
                else return true;
            }
            else return true;
        }
    }



    private void initFragment() {
        mFragment = new Fragment();
        if (fragment_home == null) {
            fragment_home = new HomeFragment();
        }
        tv1.setSelected(true);//
        tv2.setSelected(false);
        tv3.setSelected(false);

        switchContent(mFragment, fragment_home);
    }

    /**
     * 更换fragment
     *
     * @param from
     * @param to
     */
    public void switchContent(Fragment from, Fragment to) {
        if (mFragment != to) {
            mFragment = to;
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            if (!to.isAdded()) {    // 先判断是否被add过
                transaction.hide(from).add(R.id.fragment_container, to).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    @OnClick({R.id.ll_1, R.id.ll_2, R.id.ll_4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_1:
                checkPosition(1);
                break;
            case R.id.ll_2:
                checkPosition(2);
                break;
            case R.id.ll_4:
                checkPosition(4);
                break;
        }
    }


    private void checkPosition(int position) {
        tv1.setSelected(false);
        tv2.setSelected(false);
        tv3.setSelected(false);
        if (position == 1) {
            if (fragment_home == null) {
                fragment_home = new HomeFragment();
            }
            tv1.setSelected(true);
            switchContent(mFragment, fragment_home);
        } else if (position == 2) {
            if (fragment_find == null) {
                fragment_find = new FindFragment();
            }
            tv2.setSelected(true);
            switchContent(mFragment, fragment_find);
        } else if (position == 4) {
            if (fragment_mine == null) {
                fragment_mine = new MineFragment();
            }
            tv3.setSelected(true);
            switchContent(mFragment, fragment_mine);
        }

    }

    public static int flag = 0;

}
